import type { Ref } from 'vue'

export const handleFileChange = (event: any, uploadList: Ref) => {
    const files = event.target.files
    for (let i = 0; i < files.length; i++) {
        const file = files[i]
        uploadList.value.push(file)
    }
}
export const handleDirectoryChange = (event: any, uploadList: Ref) => {
    const files = event.target.files
    for (let i = 0; i < files.length; i++) {
        const file = files[i]
        uploadList.value.push(file)
    }
}
export const createFileChunk = (file: File, chunkSize: number) => {
    const chunkList: Blob[] = []
    const totalChunks = Math.ceil(file.size / chunkSize)
    for (let i = 0; i < totalChunks; i++) {
        const start = i * chunkSize
        const end = Math.min((i + 1) * chunkSize, file.size)
        chunkList.push(file.slice(start, end))
    }
    return chunkList
}
import CryptoJS from 'js-sha256'
export const sha256Hash = (plainText) => {
    return CryptoJS.sha256(plainText).toString()
}
export async function sha256(plainText) {
    const encoder = new TextEncoder()
    const data = encoder.encode(plainText)
    const hashBuffer = await crypto.subtle.digest('SHA-256', data)
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
    return hashHex
}

export function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

export const createProgressHandler = (item) => {
    return (e) => {
        item.percentage = parseInt(String((e.loaded / e.total) * 100))
    }
}

export const handleDragOver = (event: any) => {
    event.preventDefault()
}
export const handleDrop = (event: any, uploadList: Ref) => {
    event.preventDefault()
    for (const file of event.dataTransfer.items) {
        const entry = file.webkitGetAsEntry()
        if (entry.isDirectory) {
            const readDirecotry = (entry: any) => {
                if (entry.isDirectory) {
                    entry.createReader().readEntries((entries) => {
                        entries.forEach((entry) => {
                            if (entry.isFile) {
                                entry.file((f) => {
                                    uploadList.value.push(f)
                                })
                            } else readDirecotry(entry)
                        })
                    })
                }
            }
            readDirecotry(entry)
        } else entry.file((f) => uploadList.value.push(file))
    }
}
